﻿using System;
using EasyMvc.Utility;

namespace EasyMvc.Config
{
    public class ConfigContext
    {
        public ConfigDataContext DataContext { get; set; }

        public ConfigContext()
        {
            this.DataContext = new ConfigDataContext();
        }

        public virtual T Get<T>(string index = null) where T : ConfigFileBase, new()
        {
            var result = new T();
            this.VilidateClusteredByIndex(result, index);
            result = this.GetConfigFile<T>(index);

            return result;
        }

        public void Save<T>(T configFile, string index = null) where T : ConfigFileBase
        {
            this.VilidateClusteredByIndex(configFile, index);

            configFile.Save();

            var fileName = this.GetConfigFileName<T>(index);
            var content = SerializationHelper.XmlSerialize(configFile);
            this.DataContext.SaveConfigFile(fileName, content);
        }

        private T GetConfigFile<T>(string index = null) where T : ConfigFileBase, new()
        {
            var result = new T();

            var fileName = this.GetConfigFileName<T>(index);
            var content = this.DataContext.GetConfigFile(fileName);
            if (content == null)
            {
                this.DataContext.SaveConfigFile(fileName, string.Empty);
            }
            else if (content != string.Empty)
            {
                try
                {
                    result = (T)SerializationHelper.XmlDeserialize(typeof(T), content);
                }
                catch (Exception e)
                {
                    result = new T();
                }
            }

            return result;
        }

        public virtual void VilidateClusteredByIndex<T>(T configFile, string index) where T : ConfigFileBase
        {
            if (configFile.ClusteredByIndex && string.IsNullOrEmpty(index))
                throw new Exception("调用时没有提供配置文件的分区索引");
        }

        public virtual string GetConfigFileName<T>(string index = null)
        {
            var fileName = typeof(T).Name;
            if (!string.IsNullOrEmpty(index))
                fileName = string.Format("{0}_{1}", fileName, index);
            return fileName;
        }
    }
}
